document.addEventListener('DOMContentLoaded', function() {
    // 部门负责人选择框的AJAX加载
    const departmentId = window.location.pathname.split('/').pop();
    const headSelect = document.getElementById('departmentHeadID');

    if (headSelect) {
        fetch(`/department/set-head/${departmentId}/candidates`)
            .then(response => response.json())
            .then(data => {
                // 清空现有选项（保留第一个空选项）
                while (headSelect.options.length > 1) {
                    headSelect.remove(1);
                }

                // 添加新的选项
                data.forEach(user => {
                    const option = document.createElement('option');
                    option.value = user.userId;
                    option.textContent = `${user.realName} (${user.username})`;
                    headSelect.appendChild(option);
                });

                // 设置当前选中的负责人
                const currentHeadId = headSelect.dataset.currentHead;
                if (currentHeadId) {
                    headSelect.value = currentHeadId;
                }
            })
            .catch(error => console.error('加载负责人候选列表失败:', error));
    }

    // 表单验证
    const form = document.querySelector('.edit-form');
    if (form) {
        form.addEventListener('submit', function(event) {
            let isValid = true;

            // 验证部门名称
            const nameInput = document.getElementById('departmentName');
            if (!nameInput.value.trim()) {
                isValid = false;
                showError(nameInput, '部门名称不能为空');
            } else if (nameInput.value.trim().length > 50) {
                isValid = false;
                showError(nameInput, '部门名称不能超过50个字符');
            } else {
                clearError(nameInput);
            }

            // 验证部门代码
            const codeInput = document.getElementById('departmentCode');
            if (!codeInput.value.trim()) {
                isValid = false;
                showError(codeInput, '部门代码不能为空');
            } else if (codeInput.value.trim().length > 20) {
                isValid = false;
                showError(codeInput, '部门代码不能超过20个字符');
            } else {
                clearError(codeInput);
            }

            if (!isValid) {
                event.preventDefault();
            }
        });
    }

    function showError(input, message) {
        const formGroup = input.closest('.form-group');
        let errorElement = formGroup.querySelector('.error-message');

        if (!errorElement) {
            errorElement = document.createElement('div');
            errorElement.className = 'error-message';
            formGroup.appendChild(errorElement);
        }

        errorElement.textContent = message;
        input.classList.add('has-error');
    }

    function clearError(input) {
        const formGroup = input.closest('.form-group');
        const errorElement = formGroup.querySelector('.error-message');

        if (errorElement) {
            errorElement.remove();
        }

        input.classList.remove('has-error');
    }
});